import re

from django import http
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from meiduo_mall.settings.dev import logger
from apps.users.models import User
from utils.response_code import RETCODE


class RegisterView(View):
    '''用户注册'''
    def get(self,request):
        '''返回注册页面'''

        return render(request,'register.html')

    def post(self,request):
        '''
        实现用户注册
        :param request: 请求对象
        :return: 注册结果
        '''
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code = request.POST.get('sms_code')
        allow = request.POST.get('allow')

        # 校验参数
        # 1.判空
        if not all([username,password,password2,mobile,allow]):
            return http.HttpResponseForbidden('缺少必填参数！')
        # 2.判断用户名
        if not re.match(r'^\w{5,20}$',username):
            return http.HttpResponseForbidden('用户名长度在5-20')
        # 3.判断密码
        if not re.match(r'^\w{8,20}$',password):
            return http.HttpResponseForbidden('密码长度为8-20')
        # 4.判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次密码不一致！')
        # 5.判断电话号码是否是11位数字
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden('电话号码不符合正确格式！')
        # 6.判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # 判断短信验证码是否正确
        redis_code_client = get_redis_connection('sms_code')
        redis_code = redis_code_client.get("sms_%s" % mobile)

        if redis_code is None:
            return render(request, 'register.html', {'register_errmsg': '无效验证码！'})

        if sms_code.lower() != redis_code.decode().lower():
            return render(request, 'register.html', {'register_errmsg': '输入的短信验证码有误！'})

        # 校验成功后保存数据 --- 存入数据库
        try:
            # User.objects.create_user(username=username, password=password, mobile=mobile)
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            logger.error(e)
            return render(request,'register.html',{'register_message':'注册失败！'})

        # 保持会话状态
        from django.contrib.auth import login
        login(request,user)

        # 重定向到首页
        return redirect(reverse('contents:index'))

class UsernameCountView(View):
    '''判断用户名是否重复'''
    def get(self,request,username):
        '''

        :param request: 请求对象
        :param username: 用户名
        :return: JSON
        '''
        count = User.objects.filter(username=username).count()

        return http.JsonResponse({'code':RETCODE.OK,'count':count})

class MobileCountView(View):
    '''查询手机号是否重复'''
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()

        return http.JsonResponse({'code':RETCODE.OK,"count":count})